﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;

namespace BuyTrainTicket
{
    public partial class SubmitCheckCode : PhoneApplicationPage
    {
        private string pusername;
        private string ppassword;
        private string pcreatetime;
        public SubmitCheckCode()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string msgJson = "";
            if (NavigationContext.QueryString.TryGetValue("msgJson", out msgJson))
            {
                JObject respJObject = JsonConvert.DeserializeObject<JObject>(msgJson);
                string url = (string)respJObject.GetValue("url");
                string msg = (string)respJObject.GetValue("message");
                pusername = (string)respJObject.GetValue("username");
                ppassword = (string)respJObject.GetValue("password");
                pcreatetime = (string)respJObject.GetValue("createtime");
                messagetext.Text = msg;
                checkcodeimage.Source = new BitmapImage(new Uri(Util.host + "/" + url, UriKind.Absolute));
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            String username;
            settings.TryGetValue<String>("username", out username);
            String password;
            settings.TryGetValue<String>("password", out password);
            if (username == null || password == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/QueryLeftTicket.xaml", UriKind.Relative));
                return;
            }
            if (pusername == null || ppassword == null)
            {
                MessageBox.Show("参数返回错误，请重新返回查询。");
                return;
            }
            string pcheckcode = checkcode.Text;
            if (pcheckcode == null)
            {
                MessageBox.Show("请输入验证码");
                return;
            }
            string checkcodes = "username:" + pusername + ",password:" + ppassword + ",createtime:" + pcreatetime + ",checkcode:" + pcheckcode + ";";
            sendRequest(Util.host + "/servlet/Buy12306Servlet?action=typecheckcode&password=" + password + "&username=" + username + "&checkcodes=" + checkcodes + "&type=typecheckcode&version=8.1");

        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("null");

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    if ((bool)responseObj.GetValue("isSuccess") == false)
                    {
                        JToken errMsgToken = responseObj.GetValue("errMsg");
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show((string)errMsgToken);
                        });
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            Util.NavigationService.GoBack();
                            MessageBox.Show("提交成功");
                        });
                    }

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                           {
                               MessageBox.Show(response.StatusCode.ToString());
                           });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }
        }
    }
}